import React, { Component } from 'react';
import { Modal, Form, Space, Button, Input, Alert, message, Upload } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import TheTableExtend from "@/components/TheTableExtend";
import ThePagination from "@/components/ThePagination";
import TheQueryForm from '../../../components/TheQueryForm';
import TheImage from "@/components/TheImage";
import TheUpload from "@/components/TheUpload";
import TheDialog from "@/components/TheDialog";
import { dynamicMobilePage, dynamicMobileAdd, dynamicMobileEdit, dynamicMobileFakeRegister } from "@/request/petCircleUtil/sendPhone"
import store from "@/store/store"
import _ from 'lodash';
export default class SendPhone extends Component {
  constructor() {
    super()
    this.FormRef = React.createRef()
    this.state = {
      dataSource: [], //表格数据
      columns: [
        {
          title: "编号",
          dataIndex: "memberId",
          key: "memberId",
        },
        {
          title: "用户昵称",
          dataIndex: "nickName",
          key: "nickName",
        },
        {
          title: "用户虚拟手机号",
          dataIndex: "memberMobile",
          key: "memberMobile",
        },
        {
          title: "用户头像",
          dataIndex: "memberAvatar",
          key: "memberAvatar",
          render: (text, record) => {
            return <TheImage src={text} width={50} height={50} />
          }
        },
        {
          title: "操作",
          dataIndex: "goodsName",
          key: "goodsName",
          render: (text, record) => {
            return <div>
              <TheButton haspermi={['petCircleUtil:sendPhone:edit']} onClick={() => this.edit(record)}>编辑</TheButton>
            </div>
          }
        },
      ],
      newColumns: [], //重新配置表头
      pageData: {
        current: 1,
        size: 10
      },
      total: 1,
      form_show: true, // 是否显示搜索
      searchOption: [
        { field: 'nickName', label: '用户昵称', placeholder: '请输入用户昵称', required: false, rules: [], type: 'Input', defaultValue: '', },
        { field: 'mobile', label: '用户虚拟手机号', placeholder: '请输入用户虚拟手机号', required: false, rules: [], type: 'Input', defaultValue: '', otherConfig: { maxLength: 11 } }
      ],
      queryForm: {},
      title: '', //弹框标题
      isModalVisible: false, // 弹框是否显示
      fileList: [], //图片回显
      isImportVisible: false, //导入弹窗
      importPhoneList: [], // 导入文件
      memberId: '', // 用户id
    }
  }
  componentDidMount() {
    this.getData()
  }
  // 发帖账号列表
  getData = async (values) => {
    // 搜素值
    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        ...this.state.pageData, ...this.state.queryForm,
      }
      // 页面刷新时搜素缓存
      store.dispatch({
        type: 'SaveSearchValues',
        data: { pathName: 'sendPhone', ...params }
      })
      // 接口请求返回表格数据
      let res = await dynamicMobilePage({ fake: 1, ...params })
      if (res.code === 0) {
        this.setState({
          dataSource: res.data.records,
          pageData: {
            current: res.data.current,
            size: res.data.size
          },
          total: res.data.total,
        })
      }
    })
  }
  // 搜索
  onFormSearch(values) {
    this.setState({ pageData: { current: 1, size: 10 } }, () => { this.getData(values) })
  }
  // 重置搜索
  onReset() {
    this.setState({ queryForm: {} }, () => { this.pageChange(1, 10) })
  }
  // 表头显示内容
  onColumnsFilter(value) {
    this.setState({
      newColumns: value
    })
  }
  // 分页
  pageChange = (current, size) => {
    this.setState({ pageData: { current, size } }, () => { this.getData() })
  };
  // 关闭弹窗
  handleCancel = () => {
    this.setState({ isModalVisible: false, memberId: '', fileList: [] })
    this.FormRef.current.resetFields()
  }
  // 确认保存提交弹窗
  handleFinish = async (value) => {
    if (!value.memberAvatar) { delete value.memberAvatar }
    let { memberId } = this.state
    if (memberId) {
      let res = await dynamicMobileEdit({ memberId, ...value, })
      if (res.code === 0) {
        React.$message({ type: 'info', content: '编辑成功', })
        await this.getData()
        this.handleCancel()
      }
    } else {
      let res = await dynamicMobileAdd({ ...value })
      if (res.code === 0) {
        React.$message({ type: 'info', content: '新建成功', })
        await this.getData()
        this.handleCancel()
      }
    }
  }
  // 编辑
  edit(values) {
    console.log(values);
    this.setState({
      title: '发帖账号编辑',
      isModalVisible: true,
      memberId: values.memberId
    }, () => {
      this.FormRef.current.setFieldsValue({ ...values, mobile: values.memberMobile })
      this.setState({
        fileList: [{ uid: '-1', name: 'image.png', url: values.memberAvatar }],
      })
      console.log(this.state.fileList);
    })
  }
  // 新建
  add() {
    this.setState({
      title: '发帖账号新增',
      isModalVisible: true,
    })
  }
  // 照片上传
  getFileResult = (value) => {
    if (value.length && value[0] && value[0].response) {
      this.FormRef.current.setFieldsValue({ memberAvatar: value[0].response.data });
    } else {
      this.FormRef.current.setFieldsValue({ memberAvatar: null })
    }
  };
  // 导入
  importPhone = () => {
    this.setState({
      isImportVisible: true
    })
  }
  // 确认导入
  onImportPhone = () => {
    let { importPhoneList } = this.state
    let formData = new FormData();
    importPhoneList.forEach((file) => {
      formData.append('file', file);
    });
    this.importClose()
    fetch(React.$BaseUrl + '/user/api/b/user/fakeRegister', {
      method: "post",
      headers: {
        RSnetToken: sessionStorage.getItem('RSnetToken')
      },
      body: formData,
    }).then((res) => {
      res.json().then(res => {
        if (res.code === 0) {
          this.setState({ importPhoneList: [] })
          message.success('添加成功')
          this.importClose()
          this.getData()
        } else {
          message.error(res.codeMessage)
        }
      })
    }).catch((res) => {
      message.error('上传失败.');
    })
  }
  // 关闭导入弹窗
  importClose = () => {
    this.setState({ isImportVisible: false })
  }
  // 导入模板
  onDownload(url) {
    const eleLink = document.createElement('a');
    eleLink.style.display = 'none';
    eleLink.href = url;
    document.body.appendChild(eleLink);
    eleLink.click();
    document.body.removeChild(eleLink);
  }
  render() {
    const { dataSource, columns, newColumns, total, pageData, form_show, searchOption, title, isModalVisible, isImportVisible, importPhoneList, fileList } = this.state
    let fileData = {
      accept: ".xls,.xlsx,application/vnd.ms-excel",
      maxCount: 1,
      onRemove: (file) => {
        const index = importPhoneList.indexOf(file);
        const newFileList = importPhoneList.slice();
        newFileList.splice(index, 1);
        this.setState({
          importPhoneList: newFileList
        })
      },
      beforeUpload: (file) => {
        this.setState({
          importPhoneList: [file]
        })
        return false;
      },
      importPhoneList,
    };
    return (
      <div className="p-layout-box commodity-content">
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} show={form_show} option={searchOption}
          onGetValues={(values) => this.onFormSearch(values)}
          onReset={(values) => this.onReset(values)}
        >
        </TheQueryForm>
        <TheTableExtend
          columns={columns}
          onFormTrigger={() => this.setState({ form_show: !this.state.form_show })}
          onTableRefresh={() => this.getData()}
          onColumnsFilter={(value) => this.onColumnsFilter(value)}
        >
          <TheButton haspermi={['petCircleUtil:sendPhone:add']} type={'primary'} size={'middle'} onClick={() => { this.add() }}>新建</TheButton>
          <TheButton haspermi={['petCircleUtil:sendPhone:export']} type={'primary'} size={'middle'} onClick={() => { this.importPhone() }}>导入</TheButton>
          <TheButton haspermi={['petCircleUtil:sendPhone:exportEx']} type={'default'} size={'middle'} onClick={() => {
            this.onDownload("https://hqmimage.oss-cn-beijing.aliyuncs.com/%E6%89%8B%E6%9C%BA%E5%8F%B7.xlsx")
          }}>下载导入模板</TheButton>
        </TheTableExtend>
        <TheTable
          scroll={{ x: "max-content", y: "63vh" }}
          columns={newColumns}
          dataSource={dataSource}
        />
        <ThePagination
          pageNo={pageData.current}
          pageSize={pageData.size}
          total={total}
          pageChange={this.pageChange}
        />
        <Modal title={title} visible={isModalVisible} width="30%"
          onCancel={() => this.handleCancel()}
          footer={null}
        >
          <Alert style={{ marginBottom: '20px' }} message="用户虚拟手机号号段必须是111开头的：用户昵称必填" type="info" />
          <Form
            labelCol={{
              span: 8,
            }}
            wrapperCol={{
              span: 14,
            }}
            ref={this.FormRef}
            onFinish={(values) => this.handleFinish(values)}
          >
            <Form.Item
              label="用户昵称"
              name="nickName"
              rules={[
                {
                  required: true,
                  message: '请输入用户昵称',
                },
              ]}
            >
              <Input placeholder='请输入用户昵称' maxLength={10} />
            </Form.Item>
            <Form.Item
              label="用户虚拟手机号"
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '请输入用户虚拟手机号',
                },
                {
                  pattern: new RegExp(/^111\d{8}$/),
                  message: '用户虚拟手机号必须是以111开头的11位数字'
                }
              ]}
            >
              <Input placeholder='请输入用户虚拟手机号' maxLength={11} />
            </Form.Item>
            <Form.Item
              label="用户头像"
              name="memberAvatar"
            >
              <TheUpload getFileResult={(value) => this.getFileResult(value)} fileList={fileList} maxSize={10} len={1} />
            </Form.Item>
            <Form.Item wrapperCol={{
              offset: 12,
              span: 16,
            }}>
              <Space size="small" style={{ marginLeft: 10 }}>

                <Button type="default" onClick={() => this.handleCancel()}>
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  确定
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
        <TheDialog
          width={400}
          title={'导入用户'}
          visible={isImportVisible}
          handleCancel={this.importClose}
          footer={null}
        >
          <Form onFinish={this.onImportPhone}>
            <Form.Item label='上传文件' rules={[{ required: true }]} name="upFiles">
              <Upload {...fileData} >
                <Button icon={<UploadOutlined />}>选择文件</Button>
              </Upload>
            </Form.Item>
            <Form.Item>
              <div style={{ display: 'flex', justifyContent: 'flex-end', marginBottom: -30 }}>
                <Space>
                  <Button onClick={this.importClose}>取消</Button>
                  <Button type="primary" htmlType="submit">确认</Button>
                </Space>
              </div>
            </Form.Item>
          </Form>
        </TheDialog>
      </div>
    );
  }
}
